package lib;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Formula 
{
	private static FormulaEvaluator m_formula = null;
	private WorkbookInLib m_workbook;
	
	public Formula(WorkbookInLib workbook)
	{
		if(m_workbook.isUseHssf())
		{
			m_formula = new HSSFFormulaEvaluator((HSSFWorkbook)m_workbook.getRealWorkbook());
		}
		else
		{
			m_formula = new XSSFFormulaEvaluator((XSSFWorkbook)m_workbook.getRealWorkbook());
		}
	}
	
	protected static String getValue(CellInLib cell)
	{
		CellValue value = m_formula.evaluate(cell.getRealCell());
		switch (value.getCellType()) 
		{
		case HSSFCell.CELL_TYPE_BLANK:
			return "";
		case HSSFCell.CELL_TYPE_BOOLEAN:
			return value.getBooleanValue() + "";
		case HSSFCell.CELL_TYPE_NUMERIC:
		{
			double number = value.getNumberValue();
			if(number == (int)number)
			{
				return (int)number + "";
			}
			else
			{
				return number + "";
			}
		}
		case HSSFCell.CELL_TYPE_STRING:
			return value.getStringValue();
		default:
			return "";
		}
	}
}
